<?php
require_once 'BaseController.php';

/**
 * 【SP版】物件一覧 コントローラ
 */
class Mobileapi_ListController extends Mobileapi_BaseController
{

    /**
     * メインアクション
     */
    public function indexAction()
    {
        $params = $this->getParameters();

        $area = $params['Area'];
        $code = $params['Code'];
        $page = $params['Page'];
        $page = ($page == NULL || $page == '') ? 1 : intval($page);
        if ($page == 0) $page = 1;

        $page_size = $params['page_size'] = 5;
        $sort_type = $params['sort_type'] = 'sort0';

        $this->getPrefData($code);

        $params = $this->makeMainParams($params, $area, $code);
        $params = $this->makeLeftPainParams($params);
        $this->makeTemplateParams($params, $page, $page_size, $sort_type);
        $this->makeSeoParams($params);
        $this->displayBody2('result');
    }

    /**
     * メインアクション(post)
     */
    public function postAction()
    {
        $params = $this->getParameters();

        if ($params['Area'])
        {
            $area = $params['Area'];
        }
        else if ($params['search_type'])
        {
            $area = $params['search_type'];
        }

        $page = $params['page'];
        if ($page !== 'config')
        {
            $page = ($page == NULL || $page == '') ? 1 : intval($page);
            if ($page == 0) $page = 1;
        }

        $page_size = $params['page_size'];
        if (!$page_size) $page_size = 5;

        $sort_type = $params['sort_type'];
        if (!$sort_type) $sort_type = 'sort0';

        if ($area == 'shop')
        {
            $params['SrhKbn'] = Apm_Config_Search::SRHKBN_TENPOBUKKEN;
            $params['shopCd'] = $params['target_0'];
        }
        if ($params['SrhKbn'] != Apm_Config_Search::SRHKBN_TENPOBUKKEN)
        {
            $this->getPrefData($params['target_0']);
        }
        $codes = $this->extractParams($params, 'target_');
        $chous = $this->extractParams($params, 'targetchou_');

        if ($page == 'config')
        {

            $page = $params['config'] = 1;

            // 町データがあれば→取得する
            $chous = $this->extractParams($params, 'targetchou_');
            $params = $this->makeMainParams($params, $area, $codes, $chous);
            $params = $this->makeLeftPainParams($params);
            $this->makeSeoParams($params);

            // $this->_data['Mapping_params'] = $params;

            if ($params['SrhKbn'] == '01')
            {
                $this->displayBody2('hope_area');
            }
            else if ($params['SrhKbn'] == '02')
            {
                $this->displayBody2('hope_line');
            }
            else
            {
                $this->displayBody2('hope_shop');
            }
        }
        else
        {
            $codes = $this->extractParams($params, 'target_');
            $chous = $this->extractParams($params, 'targetchou_');
            if (isset($chous) && $chous != null && sizeof($chous) > 0)
            {
                $params['TownCd'] = $chous;
            }
            $params = $this->makeMainParams($params, $area, $codes);
            $params = $this->makeLeftPainParams($params);
            $this->makeTemplateParams($params, $page, $page_size, $sort_type);
            $this->displayBody2('result');
        }
    }

    public function xAction()
    {
        $params = $this->getParameters();

        $page = 1;
        $page_size = $params['page_size'] = 5;
        $sort_type = $params['sort_type'] = 'sort0';

        $this->getPrefData($params['PrefCd'][0]);

        $params = $this->makeMainParams($params);
        $params = $this->makeLeftPainParams($params);
        $this->makeTemplateParams($params, $page, $page_size, $sort_type);

        $this->displayBody2('result');
    }

    private function makeMainParams($params, $cat, $code, $chous = null)
    {
        if ($cat == 'area')
        {
            $params['SrhKbn'] = '01';

            $params = $this->addCodesToParams2($params, $code, 'PrefCd', 'CityCd');

            $model1 = new Search_Model_Selareasearch();
            $this->_data['Mapping_pref'] = $model1->getPrefNameByPrefCd($params);
            $model2 = new Search_Model_Selcyo();
            $Mapping_city = array();

            $Mapping_city = $model2->getShikucyosonNameByShikucyosonCd($params);

            // 町名
            if (isset($chous) && $chous != null && sizeof($chous) > 0)
            {
                $params['TownCd'] = $chous;
                $chou_list = $model2->getCyoNameByCyoCd($params);

                // 市区町村と町名をマージする
                $Mapping_chou = array();
                foreach ($Mapping_city as $city)
                { // 市区町村ループ

                    $city['CHOU'] = array();
                    foreach ($chou_list as $chou)
                    { // 町ループ
                        if ($city['M01_SHIKUCHOUSON_CD'] == $chou['M01_SHIKUCHOUSON_CD'])
                        {
                            $city['ISCHOU'] = 1;
                            $city['CHOU'][] = $chou;
                        }
                    }
                    $Mapping_chou[] = $city;
                }
                $this->_data['Mapping_city'] = $Mapping_chou;
            }
            else
            {
                $this->_data['Mapping_city'] = $Mapping_city;
            }
        }
        else if ($cat == 'line')
        {
            $params['SrhKbn'] = '02';

            $params = $this->addCodesToParams2($params, $code, 'PrefCd', 'StCd');
            $params = $this->makeRailCodeParams($params, 'StCd');

            $model1 = new Search_Model_Selareasearch();
            $this->_data['Mapping_pref'] = $model1->getPrefNameByPrefCd($params);

            $model2 = new Search_Model_Selensen();
            $this->_data['Mapping_ensen'] = $model2->getRailNameByRailCd($params);

            $model3 = new Search_Model_Seleki();
            $this->_data['Mapping_eki'] = $model3->getStNameByStCd($params);
        }
        else if ($cat == 'shop')
        {
            $model_shop = new Shop_Model_Detail();
            $dbParams = array();
            $dbParams['ShopCd'] = $params['target_0'];
            $shop = $model_shop->getList($dbParams);
            $this->_data['Mapping_shop'] = $shop;
        }
        if (array_key_exists('KodawariId', $params))
        {
            switch ($params['KodawariId'])
            {
                case 1:
                    $params['kodawari10'] = 'on';
                    break;
                case 2:
                    $params['built'] = 1;
                    break;
                case 3:
                    // todo:安心セキュリティ
                    break;
                case 4:
                    $params['kodawari112'] = 'on';
                    break;
                case 5:
                    $params['kodawari62'] = 'on';
                    break;
                case 6:
                    $params['kodawari7'] = 'on';
                    break;
                case 7:
                    $params['kodawari11'] = 'on';
                    break;
                case 8:
                    // todo: パノラマ画像あり(SQLで落ちる)
                    $params['kodawari2'] = 'on';
                    break;
                case 9:
                    $params['ekitoho'] = 5;
                    break;
                case 10:
                    $params['kodawari65'] = 5;
                    break;
                case 11:
                    $params['kodawari63'] = 'on';
                    break;
                case 12:
                    // todo: 3D間取り
                    break;
                case 13:
                    $params['kodawari19'] = 'on';
                    break;
                case 14:
                    // todo: 仲介手数料無料
                    break;
                case 15:
                    $params['kodawari39'] = 'on';
                    break;
                case 16:
                    $params['kodawari9'] = 'on';
                    break;
                case 17:
                    $params['kodawari15'] = 'on';
                    break;
                case 18:
                    $params['kodawari94'] = 'on';
                    break;
                case 19:
                    $params['syubetu3'] = 'on';
                    break;
                case 20:
                    $params['kodawari12'] = 'on';
                    break;
                case 21:
                    $params['kodawari95'] = 'on';
                    break;
                case 22:
                    $params['kodawari81'] = 'on';
                    break;
                case 23:
                    $params['kodawari87'] = 'on';
                    break;
                case 24:
                    $params['kodawari33'] = 'on';
                    break;
                case 25:
                    $params['kodawari112'] = 'on';
                    break;
                case 26:
                    $params['kodawari73'] = 'on';
                    break;
                case 27:
                    $params['kodawari127'] = 'on';
                    break;
                case 28:
                    $params['kodawari77'] = 'on';
                    break;
                case 29:
                    $params['kodawari8'] = 'on';
                    break;
                case 30:
                    $params['kodawari93'] = 'on';
                    break;
                case 31:
                    $params['kodawari101'] = 'on';
                    break;
                case 32:
                    $params['kodawari44'] = 'on';
                    break;
                case 33:
                    $params['kodawari90'] = 'on';
                    break;
                case 34:
                    $params['kodawari32'] = 'on';
                    break;
                case 35:
                    $params['kodawari61'] = 'on';
                    break;
                case 36:
                    $params['kodawari18'] = 'on';
                    break;
                case 37:
                    $params['syubetu3'] = 'on';
                    break;
                case 38:
                    // todo: 支援住宅(ルーティング失敗)
                    break;
                case 39:
                    // todo: 支援住宅(ルーティング失敗)
                    break;
                case 40:
                    $params['shikikin_nashi'] = 'on';
                    $params['reikin_nashi'] = 'on';
                    break;
                case 41:
                    $params['madori10'] = 'on';
                    break;
            }
        }
        $params['SORT_COLUMN'] = 'T03_YACHIN_KANRI_KYOEKI_SUM';
        $params['SORT_ORDER'] = 'ASC';

        return $params;
    }

    private function makeTemplateParams($params, $page, $page_size, $sort_type)
    {
        $this->getBukkenList($params, $page, $page_size, $sort_type);
        $meta_data = Apm_Bukkenurl::setCommonMeta($params['SrhKbn'], $params, $this->_data['research_data'], true);
        $this->_data['Mapping_page_title'] = $meta_data['new_page_title'];

        // 複数駅をまとめる
        $valsplit = explode(' ', str_replace('　', ' ', $meta_data['new_page_title']));
        if (sizeof($valsplit) > 1 && $params['SrhKbn'] != '16')
        {
            $ekis = [];

            $count = sizeof($valsplit);
            for ($i = 0; $i < $count - 1; $i++)
            {

                if (!in_array($valsplit[$i], $ekis))
                {
                    $ekis[] = $valsplit[$i];
                }
            }

            // 最後の駅

            $vals = explode(' ', Apm_Util::mb_str_replace2('の', ' ', $valsplit[$count - 1], 'SJIS'));
            if (!in_array($vals[0], $ekis))
            {
                $ekis[] = $vals[0];
            }

            $unit = '市区';
            if ($params['SrhKbn'] == '02') $unit = '駅';

            if (sizeof($ekis) == 1)
            {
                $this->_data['H1_title'] = $ekis[0] . 'の賃貸情報'; // .$vals[1];
            }
            else
            {
                $this->_data['H1_title'] = $ekis[0] . 'など' . sizeof($ekis) . $unit . 'の賃貸情報'; // .$vals[1];
            }
        }
        else
        {
            $this->_data['H1_title'] = $this->_data['Mapping_page_title'];
        }

        $this->_data['Mapping_params'] = $params;
    }

    private function makeLeftPainParams($params)
    {
        $model1 = new Search_Model_Campaignsearch();
        $this->_data['campaign'] = $model1->getCampaignsearch();
        $model1->convertData($params, $this->_data);

        $model2 = new Search_Model_Basicjyoken();
        $this->_data['basic'] = $model2->setChecked($params);

        $model3 = new Search_Model_Kodawarijyoken();
        $this->_data['kodawari'] = $model3->getKodawariJyoken($params);
        $model3->convertKodawariData($params, $this->_data);

        return $params;
    }

    private function getBukkenList($params, $page, $page_size, $sort_type)
    {
        $pager_from = ($page - 1) * $page_size;
        $pager_to = $pager_from + $page_size - 1;

        $model = new Mobileapi_Model_BukkenList();
        $model_conv = new Rstobi_Model_Converte();
        $model_common = new Rstobi_Model_Common();

        $tmp = array();
        $where = '';
        $where .= ' ' . $model_common->getKihonWhere($params, $tmp, true, true);
        $where .= ' ' . $model_common->getKodawariWhere($params, $tmp);

        $order = 'min_chinryo';
        $suborder = ',T03.T03_DAIHYO_TATEMONO_CD';
        switch ($sort_type)
        {
            case 'sort0': // お勧め→建物新着、物件階
                          // $order = 'min_chinryo';
                $order = 'max_touroku desc';
                $suborder .= ',lpad(T03.T03_KAI,5)';
                break;
            case 'sort1': // 建物：新着順、物件：新着順
                $order = 'max_touroku desc';
                $suborder .= ',T03.T03_KOUSHINBI DESC';
                break;
            case 'sort2': // 建物：最安値の含まれる建物、物件：賃料の低い順
                $order = 'min_chinryo';
                $suborder .= ',T03.T03_YACHIN_KANRI_KYOEKI_SUM';
                break;
            case 'sort3': // 建物：最高値の含まれる建物、物件：賃料の高い順
                $order = 'max_chinryo desc';
                $suborder .= ',T03.T03_YACHIN_KANRI_KYOEKI_SUM DESC';
                break;
            case 'sort4':
                $order = 'max_senyuu_menseki desc';
                $suborder .= ',T03.T03_SENYUU_MENSEKI DESC';
                break;
            case 'sort5': // 建物：築年数の新しい順、物件：階数順
                $order = 'max_tiku_nensu';
                $suborder .= ',lpad(T03.T03_KAI,5)';
                break;
        }

        $from = $model_common->getCampFrom($params);

        $dbParams = array();
        foreach ($tmp as $key => $val)
        {
            $dbParams[':' . $key] = $val;
        }

        $prefCds = "";
        $c = 0;
        foreach ($params['PrefCd'] as $cd)
        {
            $key = ":PrefCd_" . $c;
            if ($c > 0) $prefCds .= " , ";
            $prefCds .= $key;
            $dbParams[$key] = $cd;
            $c++;
        }

        if ($params['SrhKbn'] == '01' || $params['SrhKbn'] == '11')
        {

            // 町検索があれば→検索する
            $cities = array();
            $chous = array();
            if (isset($params['TownCd']))
            {
                foreach ($params['TownCd'] as $val)
                {
                    $city = substr($val, 0, 5);
                    if (!in_array($city, $cities)) $cities[] = $city;
                    $chous[] = substr($val, 2);
                }
            }
            // 町検索があれば→検索する

            $cityCds = "";
            $c = 0;
            foreach ($params['CityCd'] as $cd)
            {
                if (!in_array($cd, $cities))
                { // 町からのぞく
                    $key = ":CityCd_" . $c;
                    if ($c > 0) $cityCds .= " , ";
                    $cityCds .= $key;
                    $dbParams[$key] = substr($cd, 2);
                    $c++;
                }
            }
            $data = $model->getCountForArea($prefCds, $cityCds, $chous, $from, $where, $dbParams);

            // 物件件数
            $bukenParams = $dbParams;
            $bukenParams['favirote'] = true;
            $bukendata = $model->getCountForArea($prefCds, $cityCds, $chous, $from, $where, $bukenParams);
            // 物件件数
        }
        else if ($params['SrhKbn'] == '02')
        {
            $stCds = "";
            $c = 0;
            foreach ($params['StCd'] as $cd)
            {
                $key = ":StCd_" . $c;
                if ($c > 0) $stCds .= " , ";
                $stCds .= $key;
                $dbParams[$key] = $cd;
                $c++;
            }
            $data = $model->getCountForLine($prefCds, $stCds, $from, $where, $dbParams);

            // 物件件数
            $bukenParams = $dbParams;
            $bukenParams['favirote'] = true;
            $bukendata = $model->getCountForLine($prefCds, $stCds, $from, $where, $bukenParams);

            // 物件件数
        }
        // ショップ検索
        else if ($params['SrhKbn'] == Apm_Config_Search::SRHKBN_TENPOBUKKEN)
        {
            $data = $model->getCountForShop($params['target_0'], $from, $where, $dbParams);

            // 物件件数
            $bukenParams = $dbParams;
            $bukenParams['favirote'] = true;
            $bukendata = $model->getCountForShop($params['shopCd'], $from, $where, $bukenParams);
            // 物件件数
        }

        $count = $data['TATEMONO_COUNT'];
        $this->_data['tatemono_count'] = $bukendata['TATEMONO_COUNT']; // $count;

        $num_pages = (int) ceil($count / $page_size);
        $this->_data['num_pages'] = $num_pages;

        if ($page > 1) $this->_data['page_prev'] = $page - 1;
        if ($page < $num_pages) $this->_data['page_next'] = $page + 1;
        $this->_data['pagination'] = $this->getPagination($page, $num_pages);
        $this->_data['page'] = $page;

        $items = array();

        if ($count > 0)
        {
            $dbParams["pagerFrom"] = ($page - 1) * $page_size + 1;
            $dbParams["pagerTo"] = $pager_from + $page_size;

            if ($params['SrhKbn'] == '01' || $params['SrhKbn'] == '11')
            {
                $data = $model->getListForArea($prefCds, $cityCds, $chous, $from, $where, $order, $suborder, $dbParams);
            }
            else if ($params['SrhKbn'] == '02')
            {
                $data = $model->getListForLine($prefCds, $stCds, $from, $where, $order, $suborder, $dbParams);
            }
            else if ($params['SrhKbn'] == Apm_Config_Search::SRHKBN_TENPOBUKKEN)
            {
                $data = $model->getListForShop($params['target_0'], $from, $where, $order, $suborder, $dbParams);
            }
            $model_conv->dataConverteForBuken($data, $params, false, false);

            $prev = NULL;
            $c = -1;
            foreach ($data as $d)
            {
                $tatemono = $d['T03_DAIHYO_TATEMONO_CD'];
                if ($prev != $tatemono)
                {
                    $c++;
                    $items[] = array();
                }
                $d['MAX_CHINRYO_STR'] = (intval($d['MAX_CHINRYO']) / 10000);
                $d['MIN_CHINRYO_STR'] = (intval($d['MIN_CHINRYO']) / 10000);
                // OEM判定
                $OemFlg = ((array_key_exists('OemCd', $params) == true) && (is_null($params['OemCd']) == false) && (is_numeric($params['OemCd']) == true));
                // 物件画像取得
                $d['BUKEN_IMAGE'] = Apm_Bukkenitems::GetImageDataMain($d, $OemFlg);
                $d['FULLGAZOU_ICON'] = Apm_Bukkenitems::GetFullGazouIcon($d['BUKEN_IMAGE']);
                // キャンペーン取得
                $heyaCd = $d['T03_HEYA_CD'];
                $ret = $model->getCamp($heyaCd);
                if (!empty($ret))
                {
                    $d['M94_ITEM_ICON'] = $ret['M94_ITEM_ICON'];
                    $d['M94_CAMPAIGN_URL'] = $ret['M94_CAMPAIGN_URL'];
                    $d['M94_CAMPAIGN_NAME'] = $ret['M94_CAMPAIGN_NAME'];
                }

                $items[$c][] = $d;
                $prev = $tatemono;
            }
        }
        $this->_data['list'] = $items;
    }

    private function makeSeoParams($params)
    {
        $data = array();
        Apm_Seo::generateKodawariBlock($data, $params, array(), 1);

        for ($i = 0; $i < sizeof($data['CrossKodawari']['DATA']); $i++)
        {
            $cd = $data['CrossKodawari']['DATA'][$i]['KODAWARI_CD'];
            if (isset($params['Rkodawari' . $cd]))
            {
                $data['CrossKodawari']['DATA'][$i]['CHECKED'] = true;
            }
        }
        $this->_data['CrossKodawari'] = $data['CrossKodawari'];

        $data = array();
        Apm_Seo::generateTypeBlock($data, $params, array(), 1);
        $this->_data['CrossType'] = $data['CrossType'];
    }

    public function getPrefData($code)
    {
        $model = new Search_Model_Selareasearch();
        $c = substr($code, 0, 2);
        $this->_data['PrefInfo'] = $model->getSimpleArea($c);
        $this->_data['PrefName'] = $this->getPrefName($c);
        $this->_data['PrefNameJP'] = $this->getPrefNameJP($c);
    }

}
?>